// pages/inviteFriends/inviteFriends.js
import {
    shareOptions
} from "../../utils/access";
import api from "../../config/api";
import request from "../../utils/request";
import {
    jump,
    setStorage,
    getStorage,
    getXsScreen,
    goBack
} from "../../utils/utils";
const app = getApp()

Page({

    /**
     * 页面的初始数据
     */
    data: {
        // 是否是小屏幕尺寸
        ...getXsScreen(),
        // 邀请人数
        inviteNumber: 0,
        // 累计获得垃圾袋数量
        bagNumber: 0,
        // 弹幕列表
        barrageList: [],
        barrageTwoList: [],
        animation: {}
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 分享邀请关系
        if (options.scene) {
            var scene = decodeURIComponent(options.scene);
            console.log("scene is ", scene);
            if (scene) {
                var arr = scene.split("=");
                console.log("setStorageSync:", arr[0], "=", arr[1]);
                setStorage(arr[0], arr[1])
            }
        } else {
            const inviteUserId = options.new_invite_user_id
            console.log("hition===邀请人用户id", inviteUserId);
            if (inviteUserId) {
                setStorage('new_invite_user_id', inviteUserId)
            }
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {
        this.modal = this.selectComponent('#modal')
        this.overModal = this.selectComponent('#overModal')
        this.poster = this.selectComponent('#poster')
        if (this.showOverModal) {
            this.showOverModal = false
            this.overModal.show()
        }
        var animation = wx.createAnimation({ // 创建动画
            duration: 20000,
            timingFunction: 'linear',
        })
        this.animation = animation;
        if (this.showAnimate) {
            this.showAnimate = false
            this.textScroll()
            setInterval(() => {
                this.textScroll()
            }, 20000);
        }
    },
    textScroll() {
        console.log('0000000000')
        var animation = wx.createAnimation({ // 创建动画
            duration: 0,
            timingFunction: 'fast',
        })
        animation.left(wx.getSystemInfoSync().windowWidth)
        animation.translateX(0).step()
        this.setData({
            animationData: animation.export()
        })
        //    debugger
        // 根据屏幕大小换算文字长度
        var query = wx.createSelectorQuery();
        query.select('.barrage').boundingClientRect();
        query.exec((res) => {
            this.width = res[0].width
            this.animation.left(0)
            this.animation.translateX(-res[0].width).step()
            this.setData({
                animationData: this.animation.export()
            })
        })
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        this.getTime()
        this.getDetail()
    },
    // 获取活动时间
    async getTime() {
        let res = await request.get(api.getActivityTime, {
            activityId: 18
        }, {
            loading: false
        })
        if (res.httpStatus === 200) {
            if (res?.data?.endDate) {
                let endDate = res.data.endDate + " " + "00:00:00"
                let time = new Date(endDate.replace(/-/g, "/")).getTime() - new Date().getTime()
                if (time <= 0) {
                    this.showOverModal = true
                    if (this.showOverModal && this.overModal) {
                        this.showOverModal = false
                        this.overModal.show()
                    }
                }
            }
        }
    },
    // 获取邀请数据
    async getDetail() {
        let res = await request.get(api.inviteMessage, {}, {
            loading: false
        })
        if (res.httpStatus === 200) {
            let barrageList = []
            let barrageTwoList = []
            res.data.list.forEach((item, index) => {
                if (index % 2 === 0) {
                    barrageList.push(item)
                } else {
                    barrageTwoList.push(item)
                }
            })
            this.setData({
                inviteNumber: res?.data?.inviteNumber,
                bagNumber: res?.data?.bagNumber,
                barrageList,
                barrageTwoList
            })
            this.showAnimate = true
            if (this.showAnimate && this.animation) {
                this.showAnimate = false
                this.textScroll()
                this.timer = setInterval(() => {
                    this.textScroll()
                }, 20000);
            }

        }
    },
    // 跳转至活动规则
    jumpInviteFriendsRule() {
        if (app.isLogin()) {
            jump('inviteFriendsRule')
        } else {
            setStorage('redirectPath', '/pages/inviteFriends/inviteFriends')
            app.login()
        }
    },
    // 跳转好友邀请列表
    jumpDetail() {
        if (app.isLogin()) {
            jump('inviteFriendsList')
        } else {
            setStorage('redirectPath', '/pages/inviteFriends/inviteFriends')
            app.login()
        }
    },
    // 跳转至兑换券列表
    jumpCertificate() {
        if (app.isLogin()) {
            jump('coinCertificate')
        } else {
            setStorage('redirectPath', '/pages/inviteFriends/inviteFriends')
            app.login()
        }
    },
    // 面对面邀请
    async codeShare() {
        if (app.isLogin()) {
            const userId = getStorage('userId')
            let fileData = await request.get(api.qrcodeImage, {
                page: 'pages/inviteFriends/inviteFriends',
                scene: 'new_invite_user_id=' + userId
            }, {
                responseType: 'arraybuffer'
            })
            console.log('fileData', fileData);
            this.modal.show()
            this.initShareImg(fileData)
        } else {
            setStorage('redirectPath', '/pages/inviteFriends/inviteFriends')
            app.login()
        }
    },
    saveCode() {
        if (this.loading) return
        this.loading = true
        this.timeout = setTimeout(() => {
            this.loading = false
        }, 10000)
        this.poster?.savePicture((res) => {
            if (!res) {
                clearTimeout(this.timeout)
                this.loading = false
            }
        })
    },
    // 初始化分享图
    initShareImg(fileData) {
        const fileManager = wx.getFileSystemManager()
        const filePath = `${wx.env.USER_DATA_PATH}/${Date.now()}.jpg`
        console.log(filePath)
        fileManager.writeFileSync(filePath, fileData, 'binary')
        this.poster.init(async (vm) => {
            // 背景图
            await vm.image({
                src: 'https://image-classify.daieco.com/kejian-quanzi/sQWqy8c9rzi61dca61baa44f495d46fb456df445ed5e.png',
                width: 648,
                height: 902,
            })
            // 二维码
            await vm.image({
                src: filePath,
                width: 280,
                height: 280,
                top: 338,
                left: 184,
                radius: 2
            })
        })
    },
    modalClose() {
        this.modal.hide()
        this.loading = false
        clearTimeout(this.timeout)
    },
    back() {
        goBack()
    },
    // 点击返回按钮
    handleBack(){
        goBack()
        clearInterval(this.timer)
    },
    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {
        clearInterval(this.timer)
    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {},

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function (e) {
        if (app.isLogin()) {
            return shareOptions('newInvite', e)
        } else {
            return shareOptions('default', e, '和我一起养成垃圾分类好习惯', 'pages/inviteFriends/inviteFriends', 'https://image-classify.daieco.com/kejian-quanzi/jPqeBiUylOVBf3a2f19b53e25daca37d49ce974370cb.png')
        }
    }
})